<?php
/**
 * Created by PhpStorm.
 * User: wym
 * Date: 2016/6/20
 * Time: 16:28
 */
include_once ADMIN_PATH ."../bs/bs.automation.php";
//最美医生投票
class VoteController extends BaseController{

    function index(){
        $do_bd = new DoVote_beautiful_doctor();
        $count = $do_bd->count();
        $page = new tools\Page($count,10);
        $vote_list = $do_bd->offset($page->limit)->limit($page->pagesize)->orderby('id desc')->rows();
        $vote_add_url = $this->url('vote','vote_add');
        $vote_leave_url = $this->url('vote','leave_index');
        $votenum_add_url = $this->url('vote','add_ticket');
        $send_message_url = $this->url('vote', 'send_message');
        require $this->template;
    }

    //信息表单处理
    function vote_add(){
        $do_bd = new DoVote_beautiful_doctor();
        $list_url = $this ->url('vote','index');
        if($_POST){
            $number= $this->request('number',"",true);
            $name = $this->request('name',"",true);
            $do_bd->set_id($_GET['id']);
            $do_bd->set_name($name);
            $do_bd->set_number($number);
            $do_bd->set_sex($this->request('sex'));
            $do_bd->set_address($this->request('address'));
            $do_bd->set_keshi($this->request('keshi'));
            $do_bd->set_hospital($this->request('hospital'));
            $do_bd->set_modle_id($this->request('modle_id'));
            $do_bd->set_zhicheng($this->request("zhicheng"));
            $do_bd->set_address($this->request('address'));
            $do_bd->set_hospital($this->request('hospital'));
            $do_bd->set_dc_tel($this->request('dc_tel'));
            $do_bd->set_descript($this->request('descript'));
            $do_bd->set_descript_story($this->request('descript_story'));
            $do_bd->set_modle_id($this->request('modle_id'));
            if(!isset($_GET['id'])){
                $do_bd->set_state('0');
            }


            //上传图片开始
            $img_url = 'cache/text_img/';
            $imgs = Tools::upload_imgs($_FILES, $img_url,'pic');
            //上传图片结束
            $head_pic=$this->request('old_head_pic');
            $head_img = empty($_FILES['pic']['name'][0])?$head_pic:$imgs[0];
            $do_bd->set_head_img($head_img);

            $old_pic=$this->request('old_pic');
            $img = empty($_FILES['pic']['name'][1])?$old_pic:$imgs[1];
            $do_bd->set_img($img);
            //获取图片的尺寸
            //$size = getimagesize(G_SITE_CDN."/".$img);
            $size = getimagesize(G_SITE_CDN."/".$imgs[1]);
            $width = $size?$size[0]:$this->request('img_width');
            $height = $size?$size[1]:$this->request('img_height');
            $do_bd->set_img_width($width);
            $do_bd->set_img_height($height);
            if($do_bd->save()){

              echo "<script>alert('提交成功！');location.href='".$list_url."'</script>";
            }else{
                echo "<script>alert('提交失败！');</script>";
            }

        }else{
            $id = $_GET['id'];
            $do_bd->set_id($id);
            $info = $do_bd->where($do_bd->data)->row();
            $ajax_send_url = $this->url('vote','ajax_send_phone');

            require $this->template;
        }


    }

    //推送消息
    function  ajax_send_phone(){
        $bm = new C发微信消息();
        $infoId = $this->request('id','',true);
        $openId = $this->request('oid');

        $do_vote = new DoVote_beautiful_doctor();
        $do_vote->set_id($infoId);

        $res = $do_vote->where($do_vote->data)->count();


        if($openId){
            $msg = '测试通过';
        }else{
            $msg = '推送完毕';
            $do_vote->set_state('1');
            $do_vote->set_release_date(date('Y-m-d',time()));
        }

        if($res>0){
            if (!$do_vote->where($do_vote->data)->count() and !$openId) {
                $do_vote->save();
            }

            //给用户发送投票消息
            if ($openId) {
                $bm->send_vote($infoId,$openId);
            } else {
                $this->run_cli('vote_msg', $infoId);
            }
            $this->jsonOutPut(0, $msg);
        }else{
            $this->jsonOutPut(-1, '请添加图文消息');
        }
    }

    //给未收到消息的用户重推
    public function accept_failed_user(){
        $bm = new C发微信消息();
        $id = $this->request('id');
        $bm->ff发送咨询信息($id,'','失败');
        echo true;
    }

    //投票留言
    function  leave_index(){
        $do_bd = new DoVote_beautiful_doctor();
        $do_leave = new DoVote_leave_words();
        $where = "";
        if(isset($_GET['id'])){
            $where = array('a.bd_id'=>$_GET['id']);
        }

        $do_leave->leftJoin($do_bd,'b','a.bd_id = b.id');
        $count = $do_leave->fields('count(id)')->where($where)->count();

        $page = new tools\Page($count,10);
        $leave_list = $do_leave->fields('a.*,b.name name')->where($where)->orderby('id desc')->offset($page->limit)->limit($page->pagesize)->rows();


        $vote_add_url = $this->url('vote','vote_add');
        $vote_leave_url = $this->url('vote','leave_index');
        $leave_export_url = $this->url('vote','leave_export');
        require $this->template;
    }

    //导出留言数据
    function leave_export(){
        $do_vote = new DoVote_beautiful_doctor();
        $do_leave = new DoVote_leave_words();
        $id = $this->request('id');
        $where = "";
        if($id){
            $where = array('a.bd_id'=>$id);
        }
        $data[1]=array('姓名','身份','电话','内容','时间');
        $list = $do_leave->fields('b.name name ,a.*')->where($where)->leftJoin($do_vote,'b','b.id = a.bd_id')->rows();
        for ($i=0;$i<count($list);$i++){
            $user_status = $list[$i]['user_status']==0?'家长':'医生';
            $data[]=array("".$list[$i]['name']."","".$user_status."","".$list[$i]['tel']."","".$list[$i]['content']."","".$list[$i]['time']."");
        }
        Tools::export('vote_leave',$data);

    }

    //加票
    function cli_add_ticket()
    {
        global $argv;
        $id = $argv[3];
        $number = $argv[4];
        //半个小时执行完所有加票，计算每加一票的时间
        $min = floor( (60*30) / $number);
        $a = 0;//执行次数
        //即使Client断开(如关掉浏览器)，PHP脚本也可以继续执行.
        ignore_user_abort();
        // 执行时间为无限制，php默认的执行时间是30秒，通过set_time_limit(0)可以让程序无限制的执行下去
        set_time_limit(0);
        do {
            $do_vote = new DoVote_beautiful_doctor();
            $do_vote->set_id($id);
            $do_vote->fields('id, name,vote_num,look_num')->where($do_vote->data)->row();

            $do_vote->set_vote_num($do_vote->get_vote_num()+1);
            $do_vote->set_look_num($do_vote->get_look_num()+2);
            if($do_vote->save()){
                $a++;
            }
            sleep($min);//按设置的时间等待$min秒循环执行

        } while ($a<$number);

    }

    function add_ticket() {
        if ($_POST) {
            $id = $this->request('id','', true);
            $num = $this->request('number','',true);
            $do_vote = new DoVote_beautiful_doctor();
            $do_vote->set_id($id);
            $do_vote->fields('name,vote_num')->where($do_vote->data)->row();
            logger()->logInfo('最美医生投票——加票：姓名'.$do_vote->get_name().",当前票数".$do_vote->get_vote_num()."加票数：".$num);
            logger()->logInfo("最美医生投票——加票，开始时间:".date("Y-m-d H:i:s",time()));
            $list_url = $this ->url('vote','index');
            echo "<script>alert('提交成功！');location.href='".$list_url."'</script>";

            exec("nohup php index.php vote cli_add_ticket $id $num >> add_ticket.log &");
            logger()->logInfo('最美医生投票——加票,姓名'.$do_vote->get_name().",结束时间:".date("Y-m-d H:i:s",time()));
        } else {
            require $this->template;
        }

    }

    public function send_message(){
        require $this->template;
    }
    public function send_message_post(){
        $telephone = $this->request("telephone", '', true);
        $content = $this->request("content", '', true);
        $telephone = str_replace('，', ',', $telephone);
        $telephones = explode(',', $telephone);
        $send = new automation();
        foreach($telephones as $telephone){
            $send->send_text_messages($content, $telephone);
        }
        $this->redirect('text_message_record', 'index');
    }

    function export_vote(){
        $doVote = new DoVote_beautiful_doctor();
        $vote = $doVote->fields('name, dc_tel, vote_num')
            ->orderby("vote_num desc")->rows();
        $data[1]=array('姓名' ,
            '电话',
            '票数',
            '票差');
        foreach ($vote as $k => $v) {
            if($k>0){
                $voteDifference = $vote[$k-1]['vote_num']-$vote[$k]['vote_num'];
            }else{
                $voteDifference = 0;
            }

            $data[]=array("".$vote[$k]['name']."",
                "".$vote[$k]['dc_tel']."",
                "".$vote[$k]['vote_num']."",
                "".$voteDifference."");
        }
        Tools::export('vote',$data);
    }

}